package com.blb.day06.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blb.day06.entity.ResponseResult;
import com.blb.day06.entity.Student;
import com.blb.day06.service.StudentService;
import org.redisson.api.RBloomFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//@CrossOrigin
@RestController
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping("/student/{id}")
    public ResponseResult<Student> getStudentById(@PathVariable Long id){
        return ResponseResult.ok(studentService.getStudentById(id));
    }

    /**
     * 分页查询
     */
    @GetMapping("/students-page")
    public ResponseResult<Page<Student>> getStudentPage(@RequestParam(required = false,defaultValue = "1") Long current,
                                                        @RequestParam(required = false,defaultValue = "10") Long size){
        Page<Student> page = studentService.getStudentPage(current, size);
        return ResponseResult.ok(page);
    }

    @Autowired
    private RBloomFilter<String> rBloomFilter;

    /**
     * 初始化布隆过滤器
     * @return
     */
    @GetMapping("init-student-filter")
    public ResponseResult<String> initStudentFilter(){
        List<Student> list = studentService.list();
        //将所有id保存到过滤器中
        list.forEach(student -> {
            rBloomFilter.add(String.valueOf(student.getStuId()));
        });
        return ResponseResult.ok("ok");
    }

    /**
     * 添加学生
     * @param student
     * @return
     */
    @PostMapping("/student")
    public ResponseResult<String> addStudent(@RequestBody Student student){
        studentService.addStudent(student);
        return ResponseResult.ok(student);
    }

    /**
     * 更新
     * @param student
     * @return
     */
    @PutMapping("/student")
    public ResponseResult<String> updateStudent(@RequestBody Student student){
        studentService.updateStudentById(student);
        return ResponseResult.ok(student);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/student/{id}")
    public ResponseResult<String> deleteStudent(@PathVariable Long id){
        studentService.removeStudentById(id);
        return ResponseResult.ok(id);
    }
}
